import dbus

class TrackerClient:
	#Tracker service : [Tracker service 'name' shown, Icon used]
	
	services = {
		'Files' : ['All Files','gnome-fs-regular'],
		'Documents' : ['Documents','x-office-document'],
		'Images' : ['Images','image-x-generic'],
		'Music' : ['Music','audio-x-generic'],
		'Text Files' : ['Text Files','text-x-generic'],
		'Videos' : ['Videos','video-x-generic'],
		'Development Files' : ['Development','gnome-fs-regular']}
	defaultService = 'Files'
								
	def __init__(self):
		self.tracker = None
	
	def ensure(self):
		if self.tracker == None:
			try:
				bus = dbus.SessionBus()
				self.tracker = bus.get_object('org.freedesktop.Tracker','/org/freedesktop/tracker')
				self.searchInterface = dbus.Interface(self.tracker, 'org.freedesktop.Tracker.Search')
			except:
				self.tracker = None
		return self
		
	def search(self, searchText, service='Files', maxHits=-1, offset=0):
		if self.tracker == None:
			return None
		if not searchText:
			return []
		returnedfiles = self.searchInterface.TextDetailed(1, service, searchText, offset, maxHits)
		if len(returnedfiles) > 0:
			return returnedfiles
		else:
			return []

"""
class TrackerClient:

	def __init__(self):
		#Initialize dbus session and tracker interfaces
		bus = dbus.SessionBus()
		obj = bus.get_object('org.freedesktop.Tracker','/org/freedesktop/tracker')
		
		self.tracker_iface = dbus.Interface(obj, 'org.freedesktop.Tracker')
		self.keywords_iface = dbus.Interface(obj, 'org.freedesktop.Tracker.Keywords')
		self.search_iface = dbus.Interface(obj, 'org.freedesktop.Tracker.Search')
		self.files_iface = dbus.Interface(obj, 'org.freedesktop.Tracker.Files')
		
		self.version = self.tracker_iface.GetVersion()
		self.query_id = -1

	def search(self,text,service='Files',offset=0,max_hits=-1):
		self.resultlist = self.search_iface.Text(self.query_id, service, text, offset, max_hits)
		self.resultlist = map(lambda x: str(x),self.resultlist)
		
	def search_by_tag(self,tag,service='Files',offset=0,max_hits=-1):
		self.resultlist = self.keywords_iface.Search(self.query_id, service,tag,offset,max_hits)
		self.resultlist = map(lambda x: str(x),self.resultlist)

	def add_db_files(self,path):
		self.files_iface.Exists(path,True)
		self.files_iface.Exists(path,False)
		return True

	def add_tag(self,path,tags,service='Files'):
		self.keywords_iface.Add(service,path,tags)
		return

	#In future will be implemented live_query support
	def on_tracker_reply(self, results):
		print results
	
	def text_snippet(self, text, result, service='Files'):
		snippet = self.search_iface.GetSnippet(service, result, text)
		snippet = snippet.replace('<!--', '&lt;!--').strip()
		return snippet
		
	def on_tracker_error(self, e):
		print "Error:"+e
"""

if __name__ == "__main__":
	pass

